#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2022/3/28 10:56
# @Author : 闫峰
"""
日志封装，可设置不同等级的日志颜色
"""
import logging
import time
from logging import handlers
from typing import Text
import colorlog
from common.setting import ensure_path_sep
import os

class LogHandler:
    """ 日志打印封装"""
    # 日志级别关系映射
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }

    def __init__(
            self,
            filename: Text,
            level: Text = "info",
            when: Text = "D",
            fmt: Text = "%(levelname)-8s%(asctime)s%(name)s:%(filename)s:%(lineno)d %(message)s"
    ):
        self.logger = logging.getLogger(filename)

        if not os.path.exists(filename):
            with open(filename, 'w') as f:
                pass

        formatter = self.log_color()

        # 设置日志格式
        format_str = logging.Formatter(fmt)
        # 设置日志级别
        self.logger.setLevel(self.level_relations.get(level))
        # 往屏幕上输出
        screen_output = logging.StreamHandler()
        # 设置屏幕上显示的格式
        screen_output.setFormatter(formatter)
        # 往文件里写入#指定间隔时间自动生成文件的处理器
        time_rotating = handlers.TimedRotatingFileHandler(
            filename=filename,
            when=when,
            backupCount=3,
            encoding='utf-8'
        )
        # 设置文件里写入的格式
        time_rotating.setFormatter(format_str)
        # 把对象加到logger里
        self.logger.addHandler(screen_output)
        self.logger.addHandler(time_rotating)
        self.log_path = ensure_path_sep('\\logs\\log.log')


    @classmethod
    def log_color(cls):
        """ 设置日志颜色 """
        log_colors_config = {
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'red',
        }

        formatter = colorlog.ColoredFormatter(
            '%(log_color)s[%(asctime)s] [%(name)s] [%(levelname)s]: %(message)s',
            log_colors=log_colors_config
        )
        return formatter

    @staticmethod
    def remove_log(directory):

        import os
        import glob
          # 目录路径

        # 遍历目录下的所有文件名
        for filename in os.listdir(directory):
            if filename.endswith('.log'):
                file_path = os.path.join(directory, filename)  # 获取文件的完整路径
                os.remove(file_path)  # 删除这个文件
#
# directory = ensure_path_sep("\\logs")
# LogHandler.remove_log(directory)
now_time_day = time.strftime("%Y-%m-%d", time.localtime())
INFO = LogHandler(ensure_path_sep(f"\\logs\\info-{now_time_day}.log"), level='info')
ERROR = LogHandler(ensure_path_sep(f"\\logs\\error-{now_time_day}.log"), level='error')
WARNING = LogHandler(ensure_path_sep(f'\\logs\\warning-{now_time_day}.log'), level='warning')

# ensure_path_sep(f"\\logs\\product_strategy\\info-{now_time_day}.log")
# product_strategy_info = LogHandler(ensure_path_sep(f"\\logs\\product_strategy\\info-{now_time_day}.log"), level='info')
# product_strategy_error = LogHandler(ensure_path_sep(f"\\logs\\product_strategy\\info-{now_time_day}.log"), level='error')
# product_strategy_warning = LogHandler(ensure_path_sep(f"\\logs\\product_strategy\\info-{now_time_day}.log"), level='warning')


# INFO1 = LogHandler(ensure_path_sep(f"\\logs\\test_guiji_check\\info-{now_time_day}.log"), level='info')
# ERROR1 = LogHandler(ensure_path_sep(f"\\logs\\test_guiji_check\\error-{now_time_day}.log"), level='error')
# Listing_Error = LogHandler(ensure_path_sep(f"\\logs\\Listing_migration\\error-{now_time_day}.log"), level='error')
# WARNING1 = LogHandler(ensure_path_sep(f'\\logs\\test_guiji_check\\warning-{now_time_day}.log'), level='warning')
#
# BrandWords_list_INFO = LogHandler(ensure_path_sep(f"\\logs\\BrandWords_list\\info-{now_time_day}.log"), level='info')
# SensitiveWords_list_INFO = LogHandler(ensure_path_sep(f"\\logs\\SensitiveWords_list\\info-{now_time_day}.log"),
#                                       level='info')
# ebay_update_INFO = LogHandler(ensure_path_sep(f"\\logs\\Ebay\\info-{now_time_day}.log"), level='info')
# ebay_update_ERROR = LogHandler(ensure_path_sep(f"\\logs\\Ebay\\error-{now_time_day}.log"), level='error')
# ebay_update_WARMING = LogHandler(ensure_path_sep(f"\\logs\\Ebay\\'warning-{now_time_day}.log"), level='warning')
